import axios, { AxiosResponse, InternalAxiosRequestConfig, AxiosError } from 'axios'
import { ResultEnum } from '@/enums/httpEnum'
import { ErrorPageNameMap } from '@/enums/pageEnum'
import { redirectErrorPage, getLocalStorage, setLocalStorage } from '@/utils'
import { StorageEnum } from '@/enums/storageEnum'
const axiosInstance = axios.create({
  baseURL: import.meta.env.DEV ? import.meta.env.VITE_DEV_PATH : import.meta.env.VITE_PRO_PATH,
  timeout: ResultEnum.TIMEOUT
})

axiosInstance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = getLocalStorage(StorageEnum.EMERG_TOKEN)?.Authorization
   // console.log('token', token)
    if (token) {
      // 已经登录成功，统一添加token
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error: AxiosError) => {
    Promise.reject(error)
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (res: AxiosResponse) => {
    const { code } = res.data as { code: number }
    if (code === undefined || code === null) return Promise.resolve(res.data)
    if (code === ResultEnum.DATA_SUCCESS) {
      const user = getLocalStorage(StorageEnum.EMERG_TOKEN)
      const refresh_token = res.headers.refresh_token
      user.Authorization = refresh_token
      if (refresh_token) {
        setLocalStorage(StorageEnum.EMERG_TOKEN, user)
      }
      return Promise.resolve(res.data)
    }

    // 重定向
    if (ErrorPageNameMap.get(code)) redirectErrorPage(code)
    return Promise.resolve(res.data)
  },
  (err: AxiosResponse) => {
    console.log('error', err.code)
    // if (err.response) {
    //   const { status } = err.response
    //   console.log('UNAUTHORIZED', status)
    //   if (status) {
    //     redirectErrorPage(status)
    //   }
    // }
    if (err.code) {
      console.log('err11111or', err.code)
      redirectErrorPage(err.code)
    }
    Promise.reject(err)
  }
)

export default axiosInstance
